var gulp = require('gulp'),
    distDir = gulp.env.distDir || 'build',

    configDir = gulp.env.configDir || "compileInfo",
    revMappingFileName = "mapping_md5.json",
    requirejsRevMappingFileName = "requirejs_" + revMappingFileName,
    dependencyFileName = "dependency.json",
    compileInfoFileName = "compileInfo.json",
    ignoreList = ["!" + "*/www.zip", "!" + configDir + "/**", "!package.json", "!gulpfile.js", "!.gitignore", "!.git/**", "!.svn/**","!temp/**", "!.idea/**", "!**/*.less", "!**/*.xml", "!gulp-wex5/**", "!node_modules/**", "!test/**", "!build/**"]
    fs = require('fs'),
    //$UIPath = "/x6/UI3/v-VfAJr2-zh_CN-";
    //$UIPath = "/tuniu/v-nI3mYz-zh_CN-",
    //$UIPath = "/x5/UI2/v_4634_nol_zh_CNs_d_",
    $UIPath = gulp.env.$UIPath || "/taobao/v-ZJNfMf-zh_CN-",
    deleteFile = require('del'),
    gulpSequence = require('gulp-sequence');

function isIndexPage(contents) {
    return contents.indexOf('id="_requireJS"') != -1;
}


/*gulp.task('prepareForMd5', function () {
    gulp
        .src(['**!/core.min.js'])
        .pipe(through.obj(function (file, encoding, done) {
            var contents = String(file.contents);
            var replaceCssStr = 'define("$model/UI2/system/lib/require/css"';
            var replaceToCssStr = 'define("$model/UI2/system/lib/require/css_old"';
            contents = contents.replace(replaceCssStr, replaceToCssStr);
            var replaceCompositionStr = 'define("$model/UI2/system/lib/base/composition"';
            var replaceToCompositionStr = 'define("$model/UI2/system/lib/base/composition_old"';

            file.contents = new Buffer(contents.replace(replaceCompositionStr, replaceToCompositionStr));
            //file.contents = new Buffer("sdfdsfsd");
            done(null, file);
        }))
        .pipe(gulp.dest("."));
});*/



/*gulp.task('copyRequireJs', function () {
    gulp
        .src('gulp-wex5/require.2.1.10.js')
        .pipe(gulp.dest($UIPath.substring(1) + '/system/lib/require'));
});
gulp.task('copyCompositionJs', function () {
    gulp.src('gulp-wex5/composition.js')
        .pipe(gulp.dest($UIPath.substring(1) + '/system/lib/base'));
});

gulp.task('copyCssJs', function () {
    gulp.src('gulp-wex5/css.js')
        .pipe(gulp.dest($UIPath.substring(1) + '/system/lib/require'));
});*/


gulp.task('clean',function () {
    return deleteFile([distDir]);
});

var through = require('through2');
/*gulp.task('fixCssPluginPath', ["revAll"],function () {
 return gulp
 .src([distDir + '/!**!/system/lib/require/css.*.js'])
 .pipe(through.obj(function(file, encoding, done){
 var contents = String(file.contents);
 var replaceStr = "var url = req.toUrl(cssId + '.css');";
 file.contents = new Buffer(contents.replace(replaceStr,"var url = req.toUrl(cssId + '__css.css');"));
 done(null,file);
 }))
 .pipe(gulp.dest(distDir));
 });*/

/*gulp.task('fixRequireJsPath', ["revAll"], function () {
    return gulp
        .src([distDir + '/!**!/!*.html', distDir + '/!**!/!*.w'])
        .pipe(through.obj(function (file, encoding, done) {
            var contents = String(file.contents);
            var replaceStr = '/system/lib/require/require.2.1.10.js';
            contents = contents.replace(replaceStr, '/system/lib/require/require.2.1.10');

            var loadJsStr = '//$("head").append("<script  src=\'" + url + "\'/>");';
            var loaddJsReplaceStr = 'var url = require.toUrl("$UI" + url);';
            contents = contents.replace(loadJsStr, loaddJsReplaceStr);

            var urlStr = 'var url = window.__justep.__ResourceEngine.contextPath + urls[i];';
            var urlReplaceStr = 'var url = urls[i];';
            contents = contents.replace(urlStr, urlReplaceStr);

            var isLoadedUrlStr = 'newUrl = url;';
            file.contents = new Buffer(contents.replace(isLoadedUrlStr, 'newUrl = url.replace(/(.js|.css)$/g,"");'));

            done(null, file);
        }))
        .pipe(gulp.dest(distDir));
});*/
console.log("$UIPath:" + $UIPath);
var Path = require('path');
var RevAll = require('gulp-rev-all');
var revall = new RevAll({
    contextPath: $UIPath,
    fileNameManifest: revMappingFileName,
    fileDependency: dependencyFileName,
    debug: true,
    dontSearchFile: ['.js'],
    dontUpdateReference: [/[^\.w]\.html$/g, /\.w$/g],
    dontRenameFile: [/[^\.w]\.html$/g, /\.w$/g, "appMetadata_in_server.json"],
    transformFilename: function (file, hash) {
        var filename = file.revFilenameOriginal;
        var ext = file.revFilenameExtOriginal;
        return filename + '.md5_' + file.revHash.substr(0, this.options.hashLength) + ext;
    }
});

var is_binary_file = function (file) {
    var length = (file.contents.length > 50) ? 50 : file.contents.length;
    for (var i = 0; i < length; i++) {
        if (file.contents[i] === 0) {
            return true;
        }
    }
    return false;

};

var process$model = function (str) {
    return str.replace($UIPath, "$model/UI2");
};

var process$UI = function (str) {
    return str.replace($UIPath, "$UI");
};

var getRequireConfigPath = function (ext, requirePath, paths, revManifest, key) {
    if (ext == ".js") {
        if (key.indexOf('.w.js') != -1) {
            requirePath = requirePath.replace(".js", "").replace(/\./g, "__");
            //requirePath = requirePath.replace(".js","");
            paths[requirePath] = "/" + revManifest[key].replace(".js", "");
        } else {
            requirePath = requirePath.replace(".js", "");
            paths[requirePath] = "/" + revManifest[key].replace(".js", "");
        }

    } else if (ext == ".w") {
        //.w 后缀 是带外壳的文件不需要被require引用
        //requirePath = requirePath.replace(".js","");
        //paths[requirePath] = "/" + revManifest[key].replace(".js","");
    } else if (ext == ".html") {
        if (key.indexOf('.w.html') != -1 || key.indexOf('.html.html') != -1) {
            //.w.html 后缀 是不带外壳的片段文件 需要被text 插件引用
            requirePath = requirePath.replace(/\./g, "__");
            paths[requirePath] = "/" + revManifest[key];
        }
    } else if (ext == ".css") {
        requirePath = requirePath.replace(".css", "__css");
        paths[requirePath] = "/" + revManifest[key].replace(".css", "");
    } else {
        paths[requirePath] = "/" + revManifest[key];
    }
}


function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

var getRequireConfigPaths = function (appMappingLoads) {
    var paths = {};
    for (var index in appMappingLoads) {
        try {
            var appName = appMappingLoads[index];
            var path = Path.join(distDir + $UIPath + "/" + appName, appName + "_md5_mapping.json");
            var _paths = JSON.parse(fs.readFileSync(path), 'utf8');
            paths = extend(paths, _paths);
        } catch (e) {
        }
        ;
    }
    return paths;
};

var rebaseUrls = require('gulp-css-rebase-urls');


/*gulp.task('test', function () {
    var cssFilter = filter(['**!/datePicker.compact.css'], {restore: true});
    return gulp.src(['**!/!*.*'].concat(ignoreList))
        .pipe(cssFilter)
        .pipe(rebaseUrls())
        .pipe(cssFilter.restore)
        .pipe(gulp.dest("test"))
});*/


var filter = require('gulp-filter');
var resourceMd5;
gulp.task('revAll', function () {
    var cssFilter = filter(['**/*.css'], {restore: true});

    return gulp.src(["**/*.*"].concat(ignoreList))
        .pipe(through.obj(function (file, encoding, done) {
            if (file.isBuffer() && !is_binary_file(file)) {
                if (file.path.endsWith(".w") || file.path.endsWith(".html")) {
                    var contents = String(file.contents);
                    /*var replaceStr = /window.__justep.__ResourceEngine.contextPath \+ '/g;
                     contents = contents.replace(replaceStr,"'" + $UIPath);*/

                    try {
                        var stats = fs.lstatSync(Path.join($UIPath.substring(1), "/system/lib/require/res.js"));
                        if (stats.isFile()) {
                            contents = contents.replace("res: '$model/UI2/system/lib/require/res", "res: '" + $UIPath + "/system/lib/require/res.js");
                        }
                    }
                    catch (e) {
                    }
                    try {
                        stats = fs.lstatSync(Path.join($UIPath.substring(1), "/system/lib/require/cordova.js"));
                        if (stats.isFile()) {
                            contents = contents.replace("cordova: '$model/UI2/system/lib/require/cordova", "cordova: '" + $UIPath + "/system/lib/require/cordova.js");
                        }

                    }
                    catch (e) {
                    }

                    try {
                        stats = fs.lstatSync(Path.join($UIPath.substring(1), "/system/lib/require/w.js"));
                        if (stats.isFile()) {
                            contents = contents.replace("w: '$model/UI2/system/lib/require/w", "w: '" + $UIPath + "/system/lib/require/w.js");
                        }

                    }
                    catch (e) {
                    }
                    try {
                        stats = fs.lstatSync(Path.join($UIPath.substring(1), "/system/lib/require/css.js"));
                        if (stats.isFile()) {
                            contents = contents.replace("css: '$model/UI2/system/lib/require/css", "css: '" + $UIPath + "/system/lib/require/css.js");
                        }
                    }
                    catch (e) {
                    }

                    file.contents = new Buffer(contents);
                }
            }
            done(null, file);
        }))
        //修复css中url的写法 防止写成   justep/common/../lib/ 这种用法 应该为 justep/lib
        .pipe(cssFilter)
        .pipe(rebaseUrls())
        .pipe(cssFilter.restore)
        .pipe(revall.revision())
        .pipe(gulp.dest(distDir))
        .pipe(revall.manifestFile())
        .pipe(gulp.dest(configDir))
        .pipe((function () {
            var contentsForRequireJs;
            var contentsForCompile;
            var cwd;
            var pathBase;
            var needGenerateCompileInfo = true;
            var curMd5;
            return through.obj(function (file, encoding, done) {
                //生成供requirejs使用的paths部分的配置
                cwd = file.cwd;
                pathBase = file.base;
                var revManifest = JSON.parse(file.contents, "utf8");

                var paths = {};
                //添加$UI
                paths["$UI"] = $UIPath;
                for (var key in revManifest) {
                    var requirePath = process$model("/" + key);
                    var index = requirePath.lastIndexOf('.');
                    var ext = requirePath.substring(index, requirePath.length);
                    getRequireConfigPath(ext, requirePath, paths, revManifest, key);
                    var requirePath = process$UI("/" + key);
                    getRequireConfigPath(ext, requirePath, paths, revManifest, key);
                };
                contentsForRequireJs = new Buffer(JSON.stringify(paths, "utf8"));


                //生成供编译使用的差异文件
                var md5 = revall.md5(file.contents);
                curMd5 = md5;
                var changedFiles = [];
                var allChangedFiles = [];
                var curManifest = revManifest;
                var compileInfo = {};
                try {
                    var path = Path.join(configDir, compileInfoFileName);
                    compileInfo = JSON.parse(fs.readFileSync(path), 'utf8');

                } catch (e) {
                }
                ;
                var preMd5 = compileInfo.curMd5 ? compileInfo.curMd5 : "";
                var preManifest = compileInfo.curManifest ? compileInfo.curManifest : {};
                var baseManifest = compileInfo.baseManifest && Object.keys(compileInfo.baseManifest).length != 0 ? compileInfo.baseManifest : curManifest;

                for (var moduleID in curManifest) {
                    var path = curManifest[moduleID];
                    var prePath = preManifest[moduleID];
                    var basePath = baseManifest[moduleID];
                    if (prePath != path) {
                        changedFiles.push(distDir + "/" + path);
                    }
                    if (basePath != path) {
                        allChangedFiles.push(distDir + "/" + path);
                    }
                }
                if (baseManifest == curManifest) {
                    if (allChangedFiles.length > 0) {
                        console.error("此时allChangedFiles 不为空!");
                    }
                    allChangedFiles = changedFiles;
                }

                var compileInfo = {
                    baseManifest: baseManifest,
                    curManifest: curManifest,
                    changedFiles: changedFiles,
                    allChangedFiles: allChangedFiles,
                    curMd5: md5,
                    preMd5: preMd5
                };
                if (changedFiles.length == 0) {
                    console.log("本次编译没有文件发生变化 不需要重新生成compileInfo");
                    needGenerateCompileInfo = false;
                } else {
                    //添加首页进变化列表
                    //TODO:后续提供更加精细话的差异判断
                    for (var moduleID in curManifest) {
                        var path = curManifest[moduleID];
                        console.log("path:" + path);

                        if (path.endsWith(".w") || (path.endsWith(".html") && !path.endsWith(".w.html") && !path.endsWith(".html.html"))) {
                            changedFiles.push(distDir + "/" + path);
                            allChangedFiles.push(distDir + "/" + path);
                        }
                    }

                }
                contentsForCompile = JSON.stringify(compileInfo, "utf8");

                done(null);
            }, function (done) {
                var file = new Gutil.File({
                    cwd: cwd,
                    base: pathBase,
                    path: Path.join(pathBase, requirejsRevMappingFileName),
                    contents: new Buffer(contentsForRequireJs)
                });
                this.push(file);
                console.log("==========================================");
                console.log(cwd);
                console.log(pathBase);

                var file = new Gutil.File({
                    cwd: cwd,
                    base: pathBase,
                    path: Path.join(pathBase, "resourceMd5.json"),
                    contents: new Buffer(JSON.stringify({
                        curMd5:curMd5
                    }))
                });
                this.push(file);

                if (needGenerateCompileInfo) {
                    var file = new Gutil.File({
                        cwd: cwd,
                        base: pathBase,
                        path: Path.join(pathBase, compileInfoFileName),
                        contents: new Buffer(contentsForCompile)
                    });
                    this.push(file);
                }
                done(null);
            })
        })())
        .pipe(gulp.dest(configDir))
        .pipe(revall.dependencyFile())
        .pipe(gulp.dest(configDir))
});


gulp.task('copyResourceMd5', function() {
    return gulp.src([configDir+"/resourceMd5.json"])
        .pipe(gulp.dest(distDir + $UIPath))
});


/*gulp.task('convertMd5MappingFile', ["revAll"],function () {
 return gulp
 .src([configDir + '/' + revMappingFileName])
 .pipe(through.obj(function(file, encoding, done){
 var revManifest = JSON.parse(file.contents);
 var paths = {};
 for(var key in revManifest){
 var requirePath = process$model("/" + key);
 var index = requirePath.lastIndexOf('.');
 var ext = requirePath.substring(index, requirePath.length);

 getRequireConfigPath(ext,requirePath,paths,revManifest,key);

 var requirePath = process$UI("/" + key);
 getRequireConfigPath(ext,requirePath,paths,revManifest,key);
 };
 file.contents = new Buffer(JSON.stringify(paths));
 done(null,file);
 }))
 .pipe(gulp.dest(configDir + '/'));
 });*/



var Gutil = require('gulp-util');
gulp.task('splitMappingFile', function () {
    var cwd;
    var pathBase;
    var apps = {};
    return gulp
        .src(configDir + '/' + requirejsRevMappingFileName)
        .pipe(through.obj(function (file, enc, callback) {
            cwd = file.cwd;
            pathBase = file.base;
            var revManifest = JSON.parse(file.contents, "utf8");
            for (var key in revManifest) {
                var _key = key.replace("$model/", "").replace("UI2/", "").replace("$UI/", "").replace(/^\//g, "");
                var parts = _key.split("/");
                var appName = "system";
                if (parts.length > 1) {
                    appName = parts[0];
                }
                if (!apps[appName]) {
                    apps[appName] = {};
                }
                apps[appName][key] = revManifest[key];
            }
            ;
            callback();
        }, function (callback) {
            for (var appName in apps) {
                var file = new Gutil.File({
                    cwd: cwd,
                    base: cwd + "/" + distDir,
                    path: Path.join(cwd + "/" + distDir + $UIPath + "/" + appName, appName + "_md5_mapping_in_server.json"),
                    contents: new Buffer(JSON.stringify(apps[appName], "utf8"))
                });
                this.push(file);
                var file2 = new Gutil.File({
                    cwd: cwd,
                    base: cwd + "/" + distDir,
                    path: Path.join(cwd + "/" + distDir + $UIPath + "/" + appName, appName + "_md5_mapping.json"),
                    contents: new Buffer(JSON.stringify(apps[appName]))
                });
                this.push(file2);
            }
            callback();
        }))
        .pipe(gulp.dest(distDir));
});



var cheerio = require('gulp-cheerio');
//gulp.task('addRequireConfig',function () {
gulp.task('addRequireConfig', function () {
    return gulp
        .src([distDir + '/**/*.html', distDir + '/**/*.w'])
        .pipe(cheerio(function ($, file) {
            var _filePath = file.relative.replace(/(\/|\\)/g, "___");
            var _uiPath = $UIPath.replace(/(\/|\\)/g, "___").replace(/^___/g, "");
            var appName = _filePath.replace(_uiPath, "").replace(/^___/g, "").split("___")[0];
            var appMappingLoads = ["system"];
            appMappingLoads.push(appName);
            var config = {paths: getRequireConfigPaths(appMappingLoads)};
            config.appMappingLoads = appMappingLoads;
            config.moduleMode = "md5";
            var pathsStr = "window.__justep.resourceMode = 'md5';require.config(" + JSON.stringify(config, "utf8") + ");";
            var paths = $('<script></script>').text(pathsStr);
            paths.insertAfter('#_requireJS');
        }))
        .pipe(gulp.dest(distDir));
});

gulp.task('default', gulpSequence('clean', 'revAll', ['copyResourceMd5','splitMappingFile'],'addRequireConfig', ['genWWWDir','genWWWAllDir']));

var connect = require('gulp-connect');
gulp.task('webServer', function () {
    //console.log(JSON.stringify(paths));
    return connect.server({
        root: 'build',
        livereload: true,
        port: 8888,
        staticServerOptions:{
            maxAge:64000000
        }
    });
});


function getCompileInfo() {
    try {
        var path = Path.join(configDir, compileInfoFileName);
        var compileInfo = JSON.parse(fs.readFileSync(path), 'utf8');
        return compileInfo;
    } catch (e) {
        console.error(e);
        return {};
    }
}

/*var zip = require('gulp-zip');
 gulp.task('test',function(){
 return gulp.src([
 "build/gulp.f3a4d3bf.log",
 "build/gulpfile.d0c6445e.js",
 "build/test.b354ab06.txt",
 "build/compileInfo/compileInfo.6567c68e.json",
 "build/compileInfo/dependency.c3c6bdc5.json",
 "build/compileInfo/mapping_md5.180b405c.json",
 "build/compileInfo/requirejs_mapping_md5.d065c294.json"
 ],{base:"build"})
 .pipe(zip('www.zip'))
 .pipe(gulp.dest(distDir));
 });*/


gulp.task('genWWWDir', function () {
    var appResourceFilter = filter(function (file) {
        var path = file.path;
        if(path.indexOf(Path.join("/" + distDir + $UIPath + "/" ,"resourceMd5.json")) != -1){
            return true;
        }
        return path.indexOf('_in_server.') == -1;
    });





    return gulp.src(getCompileInfo()["changedFiles"].concat(distDir + '/**/*_md5_mapping.json'), {base: distDir})
        .pipe(appResourceFilter)
        .pipe(gulp.dest(distDir + "/www"));
});


gulp.task('genWWWAllDir', function () {
    var appResourceFilter = filter(function (file) {
        var path = file.path;
        if(path.indexOf(Path.join("/" + distDir + $UIPath + "/" ,"resourceMd5.json")) != -1){
            return true;
        }
        return path.indexOf('_in_server.') == -1;
    });
    return gulp.src(getCompileInfo()["allChangedFiles"].concat(distDir + '/**/*_md5_mapping.json'), {base: distDir})
        .pipe(appResourceFilter)
        .pipe(gulp.dest(distDir + "/www_all"));
});

/**
 *   测试部分逻辑  仿淘宝
 **/

var http = require('http');
var fs = require('fs');






function sendCompileUIRequest(done) {
    // Build the post string from an object
    var post_data = JSON.stringify({
        "androidChangeLog": "",
        "androidDownloadURL": "",
        "androidPassword": "123456",
        "appID": "C6DC500D6C400001DCDB1550E7B01989",
        "appName": "仿淘宝",
        "area": "丰台区",
        "author": "北京起步科技有限公司",
        "autoSelectPlugins": false,
        "company": "北京起步科技有限公司",
        "compileUI": false,
        "description": "Justep WeX5 仿淘宝",
        "email": "x5@justep.com",
        "extBrowser": false,
        "genAndroid": true,
        "genIOSDev": false,
        "genIOSDis": false,
        "homePage": "http://www.justep.com",
        "includeUIRes": true,
        "indexURL": "/demo/taobao/index.html",
        "iosChangeLog": "",
        "iosDevloperPassword": "",
        "iosDistributionPassword": "",
        "iosDownloadURL": "",
        "mode": "1",
        "orientation": "default",
        "packageName": "com.wex5.taobao",
        "platform": "android",
        "plugins": "",
        "pluginsConfig": [{
            "common": {
                "weixin_api_key": "1",
                "weixin_appid": "wx446deb233028960a",
                "weixin_partner_id": "1",
                "weixin_secret": "123456"
            }, "id": "com.justep.cordova.plugin.weixin.v3"
        }, {
            "common": {"redirecturi": "https://api.weibo.com/oauth2/default.html"},
            "id": "com.justep.cordova.plugin.weibo"
        }, {
            "android": {"mqtt_server": "tcp://192.168.1.97:1883"},
            "id": "com.justep.cordova.plugin.push"
        }, {
            "id": "cordova-plugin-statusbar",
            "ios": {"StatusBarOverlaysWebView": "true", "StatusBarStyle": "default"}
        }, {"common": {"unionpay_mmode": "00"}, "id": "com.justep.cordova.plugin.unionpay"}],
        "projectName": "仿淘宝",
        "province": "北京市",
        "releaseMode": "release",
        "resEncryption": false,
        "resourceAppVersion": "",
        "resourceDownloadURL": "",
        "resourceVersion": "ZJNfMf",
        "serverURL": "http://192.168.1.87:8080",
        "sourceMode": false,
        "uiResDirs": "demo/taobao",
        "useProxyBuilderServer": false,
        "version": "5.3.18",
        "webPath": "/taobao"
    }, "utf8");


    /*var post_data = JSON.stringify( {
        "androidChangeLog": "",
        "androidDownloadURL": "",
        "androidPassword": "123456",
        "appID": "C6754DBC06C00001FDE72265150010E1",
        "appName": "综合演示",
        "area": "丰台区",
        "author": "北京起步科技有限公司",
        "autoSelectPlugins": true,
        "company": "北京起步科技有限公司",
        "compileUI": true,
        "description": "Justep WeX5 综合演示",
        "email": "x5@justep.com",
        "extBrowser": false,
        "genAndroid": true,
        "genIOSDev": false,
        "genIOSDis": false,
        "homePage": "http://www.justep.com",
        "includeUIRes": true,
        "indexURL": "/portal/sample/index.w",
        "iosChangeLog": "",
        "iosDevloperPassword": "",
        "iosDistributionPassword": "",
        "iosDownloadURL": "",
        "mode": "1",
        "orientation": "default",
        "packageName": "com.justep.x5.demo",
        "platform": "android",
        "plugins": "com.justep.cordova.plugin.weixin.v3,com.justep.cordova.plugin.push,com.justep.cordova.plugin.alipay",
        "pluginsConfig": [{
            "common": {"client_id": "fd0d0861959025b5", "client_secret": "c0f18bd2d0b2b530b484a15e2ec955ac"},
            "id": "com.justep.cordova.plugin.youkuplayer"
        }, {
            "common": {
                "weixin_api_key": "C6B6989C8B400001C6F7132610DF1439",
                "weixin_appid": "wx9e5f07aedd7edd1d",
                "weixin_partner_id": "1262515301",
                "weixin_secret": "123456"
            }, "id": "com.justep.cordova.plugin.weixin.v3"
        }, {
            "common": {"redirecturi": "https://api.weibo.com/oauth2/default.html"},
            "id": "com.justep.cordova.plugin.weibo"
        }, {"android": {"mqtt_server": "abfc"}, "id": "com.justep.cordova.plugin.push"}, {
            "id": "cordova-plugin-statusbar",
            "ios": {"StatusBarOverlaysWebView": "true", "StatusBarStyle": "default"}
        }, {
            "common": {"unionpay_mmode": "00"},
            "id": "com.justep.cordova.plugin.unionpay"
        }, {
            "common": {
                "partner": "2088811446024912",
                "rsa_private": "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM3NsYcFbce3omzhiXY1Mr8nkxuHkpVFky9JBb+vnLzje+mjZIxbHDGIU//3c88H5F6CO6CPNMa036QJ9nhS6Ea7xmEGQ2JxY0JMM2bnQxhRtwwe1nV67boFzkjrOWD1loThzK3pgVkb6D6gLqANXcPSe3JAqrvouNUYvK/+75O1AgMBAAECgYBy3IdlZUlE+x+DB0lyGPTOrSa0abEM8LzZ2jaEKl4fKhOBbXjzwPH2TzEaniAbfzsc6DChRuvcrxxWcF0IALWzqyJdGNxZjlhwyVhKc4BJnn90AUXohvB83AFd2+cHurHkAE8sEO8ihDsSOon0YpKKkA/haQ8RKshTCO8RZIlugQJBAP2WkR3BbPzgHZxKR8u0woe0ZzIkUCa/+dMr8XELE6ZBj1w3uPTq4ePHto5W9MLwzN3p3lN+WcUkAM/BdzlbUyECQQDPwsf4SYCjV5hTNY7sj1sqcO4O8Ti7HnINHkefb90TsIrQjaBYNYxeEjj028yLxKkNkNUoLZQekt0jDast24IVAkBDvM5yplJYkf0W3HilH1m/Kh9Os4h9cVZoZBqQWaccB/MlbPUI5x0D3TsUdoHW+L+gn3H115BfKqjU1hbkyVJBAkEAryckVTMKayrG9aeahd7Z2e75E8nTrRUey+ZyNX0mYZodfXNY8eS7IPe14uCHEnJKn3Ax9DxwulHQcuPsI64CfQJBAPYgBMhCX6HXpLTKUuIID1dy1ENZyEEUZCouQsuPYwirOO6z4NIi8wSa98wgM0/2NJrVs1W2/l2fn8xVycd4Ykk=",
                "rsa_public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB"
            }, "id": "com.justep.cordova.plugin.alipay", "ios": {"alipay_scheme": "alipay20888114460249122"}
        }],
        "projectName": "综合演示",
        "province": "北京市",
        "releaseMode": "debug",
        "resEncryption": false,
        "resourceAppVersion": "",
        "resourceDownloadURL": "",
        "resourceVersion": "",
        "serverURL": "http://192.168.1.87:8080",
        "sourceMode": false,
        "uiResDirs": "demo/account,demo/baas,demo/comments,demo/common,demo/components,demo/config,demo/db,demo/device,demo/dialog,demo/fn,demo/misc,demo/native,demo/page,demo/sample,demo/sqlite,demo/tuniu,portal,takeout",
        "useProxyBuilderServer": false,
        "version": "5.3.18",
        "webPath": "/x6/UI3"
    });*/



    // An object of options to indicate where to post to
    //http://localhost:8080/x5/UI2/v_e42ceda8aef54d809dbada4c97ed6649l_zh_CNs_desktopd_pc/system/deploy/compile/compile.j
    var post_options = {
        host: 'localhost',
        port: '8080',
        path: '/x5/UI2/v_e42ceda8aef54d809dbada4c97ed6649l_zh_CNs_desktopd_pc/system/deploy/compile/compile.j',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

    // Set up the request
    var post_req = http.request(post_options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('Response: ' + chunk);
            done && done(chunk);
        });
    });

    // post the data
    post_req.write(post_data);
    post_req.end();
}

gulp.task("compileUI", function (done) {
    sendCompileUIRequest(function (data) {
        var flag = JSON.parse(data, "utf8").flag;
        if (flag == true) {
            done();
        } else {
            throw "编译ui失败";
        }
    });

});


gulp.task("copyWWWtoGulpDir", function (done) {
    deleteFile.sync(["taobao"]);
    return gulp.src(["D:/x5_dev/X5.3.0.3020_trunk/model/Native/仿淘宝/www/**"]).pipe(gulp.dest("."));
});


gulp.task("copyBuildDirToWWW", function () {
    var appResourceFilter = filter(function (file) {
        var path = file.path;
        return path.indexOf('_in_server.') == -1;
    });
    deleteFile.sync(["D:/x5_dev/X5.3.0.3020_trunk/model/Native/仿淘宝/build/src/platforms/android/assets/www/taobao"], {
        force: true
    });
    return gulp
        .src([distDir + '/taobao/**/*.*'])
        .pipe(appResourceFilter)
        .pipe(gulp.dest("D:/x5_dev/X5.3.0.3020_trunk/model/Native/仿淘宝/build/src/platforms/android/assets/www/taobao"));
});

gulp.task("changeMetadata", function () {
    return gulp
        .src([distDir + '/taobao/appMetadata_in_server.json'])
        .pipe(through.obj(function (file, encoding, done) {
            var contents = JSON.parse(String(file.contents), "utf8");
            var path = Path.join(configDir + "/" + "compileInfo.json");
            var compileInfo = JSON.parse(fs.readFileSync(path), 'utf8');
            //contents.resourceInfo.version = compileInfo.preMd5 + "|" + compileInfo.curMd5;
            contents.resourceInfo.curMd5 = compileInfo.curMd5;
            contents.resourceInfo.preMd5 = compileInfo.preMd5;
            contents.resourceInfo.resourceUpdateMode = "md5";
            //contents.resourceInfo.indexURL = "/" + contents.resourceInfo.version + contents.resourceInfo.indexURL;
            file.contents = new Buffer(JSON.stringify(contents, "utf8"));
            done(null, file);
        }))
        .pipe(gulp.dest(distDir + '/taobao'));
});


var gulpSequence = require('gulp-sequence');
gulp.task('test', gulpSequence('compileUI', 'copyWWWtoGulpDir', 'geneIndexHtml','default', 'changeMetadata', ['zipWWWDir', 'zipWWWAllDir'], 'copyBuildDirToWWW'));

var zip = require('gulp-zip');


gulp.task('zipWWWDir', function () {

    return gulp.src([distDir + "/www/**"], {base: distDir})
        .pipe(zip('www.zip'))
        .pipe(gulp.dest(distDir + "/taobao"));
});

gulp.task('zipWWWAllDir', function () {
    return gulp.src([distDir + "/www_all/**"])
        .pipe(zip('www_all.zip', {prependPath: "www"}))
        .pipe(gulp.dest(distDir + "/taobao"));
});


var rename = require("gulp-rename");
 gulp.task('geneIndexHtml', function () {
    return gulp.src(['**/index.w'])
     .pipe(rename(function (path) {
        path.extname = ".html"
     }))
     .pipe(gulp.dest("."));
});